package com.learn.spring_mvc.exception;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.FileNotFoundException;

/**
 * 可以返回视图也可以返回响应体
 */
@ControllerAdvice
public class ExcptionAnnotation {
    // 运行时异常，都返回统一的异常界面
    @ExceptionHandler(RuntimeException.class)
    public ModelAndView handleRuntimeException(RuntimeException e) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/error.jsp");
        return modelAndView;
    }
    
    // 区分异常类型，根据不同异常类型响应不同响应体code值，前端根据不同code值跳转不同视图
    @ExceptionHandler(FileNotFoundException.class)
    @ResponseBody
    public String handleFileNotFoundException(FileNotFoundException e) {
        return "{\"code\": 50001,\"msg\":\"FileNotFoundException\"}";
    }
}
